package com.c0nflict.server;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import java.text.SimpleDateFormat;

public class TableLogger {
	String eol = System.getProperty("line.separator");
	private BufferedWriter logFile = null;
	private Table table = null;
	private Calendar now = null;
	private Calendar nextMidnight = null;
	
	private void setLogFile() {
		if (table==null) return;
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmm");

		String logDir = System.getenv("DQ_LOG_DIR");
		if (logDir == null || logDir.trim().equals(""))
			logDir = System.getenv("TEMP");

		if (logDir == null) logDir = "/opt/dq_log/";

		try {
			logFile = new BufferedWriter(new FileWriter(logDir + table.getName() + "." + dateFormat.format(now.getTime())+".xml"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public TableLogger(Table caller) {
		if (caller.isQuiet()) {
			table = null;
			return;
		}
		table = caller;
		
		now = Calendar.getInstance();
		
		nextMidnight = Calendar.getInstance();
		nextMidnight.set(Calendar.HOUR_OF_DAY, 0);
		nextMidnight.set(Calendar.MINUTE, 0);
		nextMidnight.set(Calendar.SECOND, 0);
		nextMidnight.set(Calendar.MILLISECOND, 0);
		nextMidnight.add(Calendar.DATE, 1);
		
		setLogFile();
	}
	
	public void checkDate() {
		if (table==null) return;
		now = Calendar.getInstance();
		if (now.after(nextMidnight)) {
			setLogFile();
			
			// Set nextMidnight to the next midnight value greater than now
			while (nextMidnight.before(now))
				nextMidnight.add(Calendar.DATE, 1);
		}
	}
	
	public void logChat(String sender, String message) {
		if (table==null) return;
		checkDate();
		String type = "chat";
		
		try {
			if (message.charAt(0) == '#') 
				type = "command";
			
			StringBuffer buf = new StringBuffer();
			buf.append("<").append(type).append(">");
			buf.append("<time>").append(now.getTime().toString()).append("</time>");
			buf.append(sender).append(": ").append(message);
			buf.append("</").append(type).append(">").append(eol);
			logFile.append(buf.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}	
	}

	public void logError(String Sender, String Text) {
		if (table==null) return;
		logEvent(Sender,"error",Text);
	}
	
	public void logEvent(String Sender, String EventType, String EventText) {
		if (table==null) return;
		checkDate();
		try {
			StringBuffer buf = new StringBuffer("<event>");
			buf.append("<time>").append(now.getTime()).append("</time>");
			buf.append("<sender>").append(Sender).append("</sender>");
			buf.append("<").append(EventType).append(">").append(EventText).append("</").append(EventType);
			buf.append("></event>").append(eol);
			logFile.append(buf.toString());
			logFile.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
